#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.Text;

namespace Osh.Dvb
{
	public struct Timestamp : IComparable, IComparable<Timestamp>, IEquatable<Timestamp>
	{
		public static readonly Timestamp Zero = new Timestamp(0);

		private long _value;

		public Timestamp(long value)
		{
			_value = value & 0x1FFFFFFFF;	// 33 bits at most
		}

		public Timestamp(TimeSpan time)
		{
			_value = time.Ticks & 0x1FFFFFFFF;	// 33 bits at most
		}

		public long Value
		{
			get { return _value; }
		}

		public TimeSpan ToTimeSpan()
		{
			return TimeSpan.FromMilliseconds(_value / 90);
		}

		#region IComparable Members & Stuff
		public int CompareTo(object obj)
		{
			return _value.CompareTo(((Timestamp)obj)._value);
		}

		public override int GetHashCode()
		{
			return _value.GetHashCode();
		}

		public override bool Equals(object obj)
		{
			if(obj == null)
				return false;

			if(!(obj is Timestamp))
				return false;

			return this.CompareTo(obj) == 0;
		}

		public bool Equals(Timestamp obj)
		{
			if((object)obj == null)
				return false;

			return this.CompareTo(obj) == 0;
		}

		public static bool operator ==(Timestamp a, Timestamp b)
		{
			if(object.ReferenceEquals(a, b))
				return true;

			if(((object)a == null) || ((object)b == null))
				return false;

			return a.Equals(b);
		}

		public static bool operator !=(Timestamp a, Timestamp b)
		{
			return !(a == b);
		}
		#endregion IComparable Members & Stuff
		
		#region IComparable<Timestamp> Members
		public int CompareTo(Timestamp other)
		{
			return _value.CompareTo(other._value);
		}
		#endregion

		#region IEquatable<Timestamp> Members
		bool IEquatable<Timestamp>.Equals(Timestamp other)
		{
			return _value == other._value;
		}
		#endregion
	}
}
